# apps/imports/serializers.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from django.utils.translation import gettext_lazy as _
from .models import ImportLog

class ImportLogSerializer(serializers.ModelSerializer):
    # 自定义只读字段，显示 choice 的可读标签
    import_type_label = serializers.CharField(
        source='get_import_type_display',
        read_only=True,
        label=_("导入类型显示")
    )
    status_label = serializers.CharField(
        source='get_status_display',
        read_only=True,
        label=_("状态显示")
    )

    # 可选：显示操作人信息（简化版）
    importer_name = serializers.CharField(
        source='importer.get_full_name',  # 或 username，根据 User 模型定义
        read_only=True,
        label=_("操作人姓名")
    )

    class Meta:
        model = ImportLog
        fields = [
            'id',
            'file_name',
            'file_size',
            'total_count',
            'success_count',
            'fail_count',
            'error_log',
            'importer',
            'importer_name',
            'import_type',
            'import_type_label',
            'status',
            'status_label',
            'started_at',
            'completed_at',
            'created_at',
        ]
        read_only_fields = [
            'created_at',
            'importer_name',
            'import_type_label',
            'status_label',
        ]
        extra_kwargs = {
            'success_count': {'required': False},  # 允许可选更新
            'fail_count': {'required': False},
            'error_log': {'required': False},
            'completed_at': {'required': False},
        }
    def validate(self, attrs):
        success = attrs.get('success_count', None)
        if success is None:
            return attrs

        # 从 instance 获取 total_count（更新场景）
        total = not self.instance and attrs.get('total_count', None) or self.instance.total_count

        if success > total:
            raise serializers.ValidationError({
                "success_count": _("成功导入数不能大于总记录数。")
            })
        return attrs

    def create(self, validated_data):
        # 可在此设置 importer 为当前用户（如果视图传入）
        # 例如：request.user
        return super().create(validated_data)

    def update(self, instance, validated_data):
        # 可添加状态变更校验等业务逻辑
        return super().update(instance, validated_data)


class ImportLogListSerializer(serializers.ModelSerializer):
    """
    列表专用序列化器，减少字段，提升性能
    """
    status_label = serializers.CharField(source='get_status_display', read_only=True)
    importer_name = serializers.CharField(source='importer.get_full_name', read_only=True)
    duration = serializers.SerializerMethodField(label=_("耗时（秒）"))

    class Meta:
        model = ImportLog
        fields = [
            'id',
            'file_name',
            'file_size',
            'total_count',
            'success_count',
            'fail_count',
            'importer_name',
            'import_type',
            'status',
            'status_label',
            'started_at',
            'completed_at',
            'created_at',
            'duration',
        ]
        read_only_fields = fields

    def get_duration(self, obj) -> float:
        """
        计算导入耗时（秒），如果已完成
        """
        if obj.started_at and obj.completed_at:
            return (obj.completed_at - obj.started_at).total_seconds()
        return None


class ImportLogCreateSerializer(serializers.ModelSerializer):
    """
    用于创建导入任务的序列化器（前端上传文件时使用）
    注意：通常 file_name 和 file_size 由视图处理，也可由前端传入
    """
    class Meta:
        model = ImportLog
        fields = [
            'file_name',
            'file_size',
            'import_type',
            'importer',  # 通常由视图自动填充 request.user
        ]
        # 注意：importer 通常不应由前端指定，建议在视图中设置
        extra_kwargs = {
            'importer': {'required': False},  # 视图中设置
        }

    def validate_file_size(self, value):
        if value < 0:
            raise serializers.ValidationError(_("文件大小不能为负数。"))
        return value